import json
from web.db.manage_db.manage_user import *
from django.http.response import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from web.utils.request import api
from web.db.bean import user_bean
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view

@csrf_exempt
def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        passwod = request.POST.get("password")
        if valid_login(username, passwod):
            print(username,passwod)
            user = User.objects.get(username=username)
            response = user_bean.user_to_content(user)
            return JsonResponse(response)
    return api.sendmsg("fail")


@csrf_exempt
def logout(request):
    return api.sendmsg('success')


from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
    description = serializers.CharField(required=False)
    class Meta:
        model = User
        fields = "__all__"

class UserView(APIView):
    """
    /api/getalluser/

    """
    def get(self, request):
        user_list = User.objects.all()
        serializer = UserSerializer(instance=user_list, many=True)
        return Response(serializer.data)

    def post(self, request):
        """
        /api/regist/,注册新用户
        :param request:
        :return:
        """
        username = User.objects.filter(username=request.data['username']).first()
        email = User.objects.filter(email=request.data['email']).first()
        if (username or email):
            return Response({"message": "fail"})
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(id=get_newid())
            print(serializer.data)
            return Response({"message": "success"})
        else:
            return Response({"message": "fail"})


class UserDetail(APIView):
    def get(self, request, id):
        """
        /api/get_user_byid/
        :param request:
        :param id:
        :return:
        """

        # 如果是user_name查询，int()函数就会引发ValueError异常
        user_obj = User.objects.filter(id=id).first()
        serializer = UserSerializer(instance=user_obj, many=False)
        return Response(serializer.data)

    def put(self, request):
        """
        /api/modify_user_info/
        :param request:
        :return:
        """
        # 获取当前登录的用户信息
        user = request.user
        new_username = request.data.get["new_username"]
        new_email = request.data.get["new_email"]
        if new_username:
            existing_username = User.objects.filter(username=new_username).exclude(id=user.id)
            if existing_username:
                return Response({"message": "fail"})
        if new_email:
            existing_email = User.objects.filter(email=new_email).exclude(id=user.emal)
            if existing_email:
                return Response({"message": "fail"})
        serializer = UserSerializer(instance=user, data=request.data, many=False)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)

@api_view(['POST'])
def get_user(request):
    user = User.objects.filter(username=request.data.get('username'))
    serializer = UserSerializer(instance=user, many=True)
    return Response(serializer.data)





